package com.xiyi.shouxin.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.xiyi.shouxin.dao.admin.AdminRepository;
import com.xiyi.shouxin.dao.admin.RoleRepository;
import com.xiyi.shouxin.dao.user.PiciRecordRepository;
import com.xiyi.shouxin.entity.admin.Admin;
import com.xiyi.shouxin.entity.admin.Role;
import com.xiyi.shouxin.entity.admin.mapper.AdminMapper;
import com.xiyi.shouxin.entity.admin.mapper.RoleMapper;
import com.xiyi.shouxin.entity.user.PiciRecord;
import com.xiyi.shouxin.exception.CommonException;
import com.xiyi.shouxin.global.RoleEnum;
import com.xiyi.shouxin.view.pojo.AdminView;
import com.xiyi.shouxin.view.pojo.ItemPage;
import com.xiyi.shouxin.view.pojo.PiciRecordView;

@Service
public class PiciRecordService {
    @Autowired
    private PiciRecordRepository piciRecordRepository;
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private RoleRepository roleRepository;

    public ItemPage<PiciRecordView> findPiciRecordList(Long adminId, Date startTime, Date endTime,
            int page, int size)
            throws Exception {
        List<PiciRecordView> list = new ArrayList<>();
        List<PiciRecord> result = new ArrayList<>();
        int total = 0;
        Sort sort = Sort.by(Direction.DESC, "id");
        if (adminId != null) {
            Admin admin = adminRepository.findById(adminId, new AdminMapper());
            if (admin == null) {
                return new ItemPage<PiciRecordView>(list, total);
            }
            Role role = roleRepository.findById(admin.getRoleId(), new RoleMapper());
            if (role != null && RoleEnum.SUPER.getRole().equals(role.getRoleName())) {
                adminId = null;
            }
        }

        result = piciRecordRepository.findByMultiConditionsByPage(adminId, startTime, endTime, sort, page, size);
        total = piciRecordRepository.countByMultiConditions(adminId, startTime, endTime);

        for (PiciRecord pici : result) {
            Admin admin = null;
            if (pici.getAdminId() != null) {
                admin = adminRepository.findById(pici.getAdminId(), new AdminMapper());
            }
            PiciRecordView view = new PiciRecordView(pici, new AdminView(admin, null));
            list.add(view);
        }
        return new ItemPage<PiciRecordView>(list, total);
    }

    /*
     * 删除批次
     */
    public void delPiciRecord(List<Long> piciIds) throws CommonException {
        if (piciIds == null || piciIds.isEmpty()) {
            return;
        }
        piciRecordRepository.delByIds(piciIds);
    }

}
